﻿Public Class DinnersController
    Inherits System.Web.Mvc.Controller

    Dim dinnerRepository As New DinnerRepository
    '
    ' GET: /Dinners/

    Function Index() As ActionResult
        'Response.Write("<h1>Coming Soon: Dinners</h1>")
        Dim dinners = dinnerRepository.FindUpcomingDinners.ToList
        ViewData("Model") = dinners
        Return View()
    End Function

    Function Details(ByVal id As Integer) As ActionResult
        'Response.Write("<h1>Details DinnerID: " & id & "</h1>")
        Dim dinner = dinnerRepository.GetDinner(id)
        If dinner Is Nothing Then
            Return View("NotFound")
        Else
            ViewData("Model") = dinner
            Return View()
        End If
    End Function

    Function Edit(ByVal id As Integer) As ActionResult
        Dim dinner = dinnerRepository.GetDinner(id)
        ViewData("Model") = dinner
        Return View()
    End Function

    <AcceptVerbs(HttpVerbs.Post)>
    Function Edit(ByVal id As Integer, ByVal formValues As FormCollection) As ActionResult
        Dim dinner = dinnerRepository.GetDinner(id)
        Try
            UpdateModel(dinner)

            dinnerRepository.Save()

            Return RedirectToAction("Details", New With {.id = dinner.DinnerID})
        Catch
            ModelState.AddRuleViolations(dinner.GetRuleViolations)
            ViewData("Model") = dinner
            Return View()
        End Try
    End Function

    Function Create() As ActionResult
        Dim dinner As New Dinner With {.EventDate = Now.AddDays(7)}
        ViewData("Model") = dinner
        Return View()
    End Function

    <AcceptVerbs(HttpVerbs.Post)>
    Function Create(ByVal dinner As Dinner) As ActionResult
        If ModelState.IsValid Then
            Try
                dinner.HostedBy = "SomeUser"
                dinnerRepository.Add(dinner)
                dinnerRepository.Save()
                Return RedirectToAction("Details", New With {.id = dinner.DinnerID})
            Catch
                ModelState.AddRuleViolations(dinner.GetRuleViolations)
            End Try
        End If
        ViewData("Model") = dinner
        Return View()
    End Function

    Function Delete(ByVal id As Integer) As ActionResult
        Dim dinner = dinnerRepository.GetDinner(id)
        If dinner Is Nothing Then
            Return View("NotFound")
        Else
            ViewData("Model") = dinner
            Return View()
        End If
    End Function

    <AcceptVerbs(HttpVerbs.Post)>
    Function Delete(ByVal id As Integer, ByVal confirmButton As String) As ActionResult
        Dim dinner = dinnerRepository.GetDinner(id)
        If dinner Is Nothing Then
            Return View("NotFound")
        End If

        dinnerRepository.Delete(dinner)
        dinnerRepository.Save()

        Return View("Deleted")
    End Function
End Class
